import { mapActions, mapState, mapGetters, mapMutations } from "vuex";
import screenFull from "screenfull";
import _ from "lodash";
export default {
  computed: {
    ...mapState({
      G_Locale: (state) => state.locale, //语言种类
      G_Setting: (state) => state.setting, //设置
      G_OpenedPage: (state) => state.admin.layout.opened, //tabs已经打开的页
      G_CurrentPage: (state) => state.admin.layout.currentPage, //tabs当前活动页
      G_Menu: (state) => state.admin.layout.menu, //tabs当前导航组
      G_IsMobile: (state) => state.admin.layout.isMobile,
      G_Account: (state) => state.admin.layout.currentAccount,
      G_OpenMenuName: (state) => state.admin.layout.openMenuName,
      G_ActiveMenuName: (state) => state.admin.layout.activeMenuName,
    }),
    G_ENV() {
      return process.env.NODE_ENV === "development";
    },
  },
  mounted() {
    this.t = this.$t;
  },
  methods: {
    ...mapMutations({
      i_SetLocale: "setLocale",
    }),
    ...mapMutations("admin/layout",{
      i_setActiveMenuName:'setActiveMenuName',
      i_setOpenMenuName:'setOpenMenuName'
    }),
    G_SetLocale(locale) {
      this.i_SetLocale(locale);
      this.$set(this.$i18n, "locale", locale);
    },
    ...mapActions("admin/layout", {
      G_AddPage: "addPage",
      i_SetPage: "setPage",
      i_RemovePage: "removePage",
      G_MovePage: "movePage",
      i_login: "login",
      i_init: "init",
    }),
    G_LoadLayout(valid, values) {
      this.$router.replace(this.$route.query.redirect || "/StarCloud");
    },
    G_Login(valid, values) {
      if (valid) {
        this.i_login({ values, router: this.$router }).then((data) => {
          this.G_LoadLayout();
        });
      }
    },
    G_logout() {
      this.$router.replace("/login");
      this.i_init();
    },
    G_RemovePage(pageName) {
      this.i_RemovePage(pageName).then((page) => {
        if (!!page) {
          if (this.$route.fullPath !== page.fullPath) {
            this.$router.push(page.fullPath);
          }
        } else {
          this.G_LoadLayout();
        }
      });
    },
    G_SetPage(pageName) {
      this.i_SetPage(pageName).then((page) => {
        if (page) {
          this.$router.push(page.fullPath);
        }
      });
    },
    G_Download(table, filename = "The original data", columns, data) {
      table.exportCsv({
        filename: filename,
        columns: columns,
        data: data,
      });
    },
    G_Export(filename = "The original data", columns, data) {
      this.$Table.export({
        type: "xlsx", // 或 csv
        fileName: filename,
        columns: columns,
        data: data,
      });
    },
    G_Upload(file, fn) {
      this.$Table.import({
        type: "xlsx",
        file: file,
        finish: (res) => fn(res),
      });
      return true;
    },
    G_Fullscreen(tableFullscreen, el) {
      tableFullscreen = !tableFullscreen;
      if (tableFullscreen) {
        screenFull.request(el);
      } else {
        screenFull.exit();
      }
      return tableFullscreen;
    },
    _clone(obj) {
      return this.tools.lodash.cloneDeep(obj);
    },
    _merge() {
      return this.tools.lodash.merge(...arguments);
    },
    _clear(arr) {
      arr.splice(0, arr.length);
    },
    _shift(arr) {
      arr.shift();
    },
    _unShift(arr) {
      arr.unshift();
    },
    _push(arr, map) {
      arr.push(map);
    },
    _pop(arr) {
      arr.pop();
    },
    _replace(arr, index, map) {
      arr.splice(index, 1, map);
    },
    _replaceMap(arr, map, key) {
      let index = arr.findIndex((d) => d[key] === map[key]);
      if (index != -1) {
        arr.splice(index, 1, map);
      }
      return arr;
    },
    _remove(arr, index) {
      arr.splice(index, 1);
    },
    _removeMap(arr, map, key) {
      let index = arr.findIndex((d) => d[key] === map[key]);
      if (index != -1) {
        arr.splice(index, 1);
      }
      return arr;
    },
    _find(arr, key, value) {
      return arr.find((d) => d[key] === value);
    },
    _sort(arr, key, order) {
      if (order === "asc") {
        return arr.sort((a, b) => {
          return a[key] > b[key] ? 1 : -1;
        });
      } else {
        return arr.sort((a, b) => {
          return a[key] < b[key] ? 1 : -1;
        });
      }
    },
    _filter(arr, key, value) {
      return arr.filter((d) => d[key] === value);
    },
    _pick(arr, key) {
      return arr.map((d) => d[key]);
    },
    _union(arr1, arr2) {
      //并集
      return Array.from(new Set([...arr1, ...arr2]));
    },
    _cross(arr1, arr2) {
      //交集
      return Array.from(new Set(arr1.filter((item) => arr2.includes(item))));
    },
    _diffSingle(arr1, arr2) {
      //arr1中不在arr2中
      return Array.from(new Set(arr1.filter((item) => !arr2.includes(item))));
    },
    _diff(arr1, arr2) {
      //差集
      return Array.from(
        new Set(
          this._union(arr1, arr2).filter(
            (item) => !this._cross(arr1, arr2).includes(item)
          )
        )
      );
    },
    _set(map, key, value) {
      this.$set(map, key, value);
    },
    _del(map, key) {
      this.$delete(map, key);
    },
    _subObject(map, path, defaultValue = null) {
      return this.tools.subObject(map, path, defaultValue);
    },
    // _hanldeFilter(filter, additional, like = true) {
    //   this.tools.deleteInvalid(filter); //删除查询项中属性值为空的查询条件
    //   filter = {
    //     //修改原值
    //     ...additional,
    //     ...filter,
    //   };
    //   let newFilter = "";
    //   if (this.tools.isReal(filter)) {
    //     newFilter = this.tools.getModelFilter(filter, like ? "like" : "=");
    //     return newFilter;
    //   } else {
    //     return false;
    //   }
    // },
    // _$exec(method,...args){
    //     if(this.anc&&this.anc[method]){
    //     if (process.env.NODE_ENV === "development") {
    //         console.log(`anc.${method}:`,arguments);
    //         }
    //         return this.anc[method](...args);
    //     }else{
    //         console.log(`anc.${method}不存在`)
    //     }
    // },
    _$queryByPage(
      clzs,
      pageNavigation,
      filter = {},
      hierValueCondition = "",
      orderBy = "",
      hiddenHierData = true,
      like = false
    ) {
      return clzs
        .queryByPage(
          pageNavigation.pageNumber,
          pageNavigation.pageSize,
          filter,
          hierValueCondition,
          orderBy,
          hiddenHierData,
          like
        )
        .then((flag) => {
          if (flag) {
            pageNavigation.total = clzs.total;
          }
          return flag;
        });
    },
    _$queryByIds(clzs, ids) {
      return clzs.queryByIds(ids);
    },
    _$query(clzs, filter, like = false) {
      return clzs.query(filter, like);
    },
    _$delete(clzs, filter, like = false) {
      return clzs.delete(filter, like);
    },
    _$deleteById(clzs, id) {
      return clzs.deleteById(id);
    },
    _$deleteByIds(clzs, ids) {
      return clzs.deleteByIds(ids);
    },
    _$add(clz, record = clz.record) {
      return clz.add(record);
    },
    _$addAndInitWeb(clz, record = clz.record) {
      return clz.addAndInitWeb(record);
    },
    _$update(clz, record = clz.record) {
      // return clz.update(record);
    },
    _$validateAll(forms, success, fail) {
      let valid = [];
      forms.map((form) => {
        valid.push(form.validate());
      });

      Promise.all(valid)
        .then((res) => {
          //都通过了
          for (let i = 0; i < res.length; i++) {
            if (!res[i]) {
              if (typeof fail === "function") {
                fail(false);
              }
              console.log("err", res);
              return false;
            }
          }
          if (typeof success === "function") {
            success(true);
          }
          return true;
        })
        .catch((err) => {
          console.log("err", err);
          if (typeof fail === "function") {
            fail(false);
          }
          return false;
        });
    },
    _$deleteConfirm(ok, cancel) {
      this.$Modal.confirm({
        title: "确认删除？",
        cancelText: "取消",
        onOk: ok ? ok : () => {},
        onCancel: cancel ? cancel : () => {},
      });
    },
    _$requireInfo() {
      this.$Message.info("请填写必填内容");
    },
    _$getHierItem(hier, name) {
      return hier.content.find((item) => item.name == name);
    },
    _$getHierItemField(hier, name, field) {
      let item = this._$getHierItem(hier, name);
      if (item) {
        return item[field];
      } else {
        return null;
      }
    },
    _$setFilteStr(filter, like = true) {
      if (!!filter && filter.constructor === Object) {
        for (let key in filter) {
          (filter[key] === "" || filter[key] === null) && delete filter[key];
        }
      } //删除查询项中属性值为空的查询条件
      filter = this.bulidFilter(filter, like ? "like" : "=");
      return filter;
    },
    bulidFilter(filterMap, sign = "like") {
      let arr = [];
      if (!!filterMap) {
        Object.keys(filterMap).map((key) => {
          let curItem = filterMap[key];
          let type = typeof curItem;
          let strWrap = type === "number" || type === "boolean" ? "" : "'";

          if (curItem !== "" && curItem !== undefined && curItem !== null) {
            if (
              sign === "like" &&
              strWrap &&
              
              key != "type" &&
              key != "id"
            ) {
              arr.push(`${key} like ${strWrap}%${curItem}%${strWrap}`);
            } else {
              arr.push(`${key} ${"=="} ${strWrap}${curItem}${strWrap}`);
            }
          }
        });
      }
      return arr.join(" && ");
    },
    _$getOptionValue(options, value, key = "label") {
      let dataValue = "";
      let index = options.findIndex((d) => d.value === value);
      if (index !== -1) {
        dataValue = options[index][key];
      }
      return dataValue;
    },
    _getModelFields(name, ...args) {
      let map = {};
      args.map((key) => {
        map[key] = this.models[name][key];
      });
      return map;
    },
    _getModelRecord(name) {
      return this.models[name].clz.record;
    },
    _setVmValue(name, key, value) {
      _.set(this.vms[name], key, value);
    },
    _getModelTpl(name) {
      return this.$modelObject.getTpl(this.models[name].modelType);
    },
    _setDataSet(name, data) {
      this.dataSet[name] = data;
    },
    _modalShow(name) {
      _.set(this.vms[name], "config.show", true);
    },
    _modalClose(name) {
      _.set(this.vms[name], "config.show", false);
      _.set(this.vms[name], "config.loading", false);
    },
    _tableLoading(name) {
      _.set(this.vms[name], "loading", true);
    },
    _tableUnLoading(name) {
      _.set(this.vms[name], "loading", false);
    },
    _resetForm(name) {
      this.vms[name].resetFields();
    },
    _$getOptions(records, optionsName) {
      this[optionsName] = records.map((ele) => {
        return {
          value: ele.id,
          label:
            ele.values.sf_code +
            "_" +
            ele.values.sf_name +
            "_" +
            ele.values.modelName,
        };
      });
    },
  },
};
// :include="keepAlive"
